<template>
  <template v-if="browserVersion >= 71 && browserVersion <= 74">
    <div class="ant-code-box-demo">
      <a-upload-dragger
        v-model:file-list="defaultList"
        :headers="header"
        :action="uploadUrl"
        :accept="fileAccept"
        multiple
        @change="antdHandleChange"
      >
        <el-button type="primary">点击上传</el-button>
      </a-upload-dragger>
    </div>
  </template>
  <template v-else>
    <el-upload
      :disabled="disabled"
      :list-type="type"
      :file-list="defaultList"
      class="upload-demo"
      :drag="drag"
      :headers="header"
      :action="uploadUrl"
      multiple
      :limit="max"
      :on-error="uploadError"
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :on-exceed="onExceed"
      :accept="fileAccept"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div v-if="drag" class="el-upload__text">
        最多数量{{ max }};将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">{{ tip }}</div>
      </template>
    </el-upload>
  </template>
  <el-image-viewer
    @close="closeImgViewer"
    :url-list="imageList"
    v-if="imageList.length > 0"
    :initial-index="previewIndex"
  ></el-image-viewer>
  <el-dialog
    width="30%"
    title="播放视频"
    v-model="isVisble"
    @closed="diaglogCloed"
  >
    <x-m-player ref="refPalyer" :url="videoUrl"></x-m-player>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isVisble = false">取 消</el-button>
        <el-button type="primary" @click="isVisble = false">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisiblePdf">
    <PDF :src="pdfUrl"></PDF>
  </el-dialog>
</template>
<script setup>
  import { ref, watch } from 'vue'
  import { UploadFilled } from '@element-plus/icons-vue'
  import { useUpload, uploadNetTools } from '@/hooks/elementUI/useUpload.js'
  import { useStore } from 'vuex'
  import aUploadDragger from 'ant-design-vue/lib/upload' // 加载 JS
  import 'ant-design-vue/lib/upload/style/css'
  import { InboxOutlined } from '@ant-design/icons-vue'
  import XMPlayer from '@/components/XMPlayer'
  import common from '@/utils/common.js'
  import PDF from '@/components/PDF'
  const props = defineProps({
    multiple: {
      type: Boolean,
      default: false,
    },
    tip: {
      type: String,
      default: '',
    },
    modelValue: {
      type: String,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: () => {
        return 'text'
      },
    },
    drag: {
      type: Boolean,
      default: () => {
        return true
      },
    },
    max: {
      type: Number,
      default: () => {
        return 10
      },
    },
    maxFileSize: {
      type: Number,
      default: () => {
        return null
      },
    },
    fileAccept: {
      type: String,
      default: () => {
        // img video
        // img '.png,.jpg,.jpeg,.gif,application/pdf'
        // video 'video/*'
        return '.png,.jpg,.jpeg,.gif,application/pdf'
      },
    },
  })
  const videoType = 'video/*'
  const store = useStore()
  const emits = defineEmits(['update:modelValue'])
  // const d = reactive({ dic: {}, imageList: [] })
  const browserVersion = store.getters.browserVersion
  // 存放对象
  const listObj = ref({})
  // 默认数据
  const defaultList = ref([])
  // 预览器的默认参数
  const imageList = ref({})
  const { checkAllSuccess, removeFile, uploadSuccess, uploadBefore } =
    useUpload(listObj)
  const { header, uploadUrl } = uploadNetTools()

  watch(
    () => props.modelValue,
    (val) => {
      if (val) {
        const tmp = JSON.parse(val).map((item) => {
          if (!item.url) item.url = item.data
          item.name = decodeURIComponent(item.name)
          return item
        })
        defaultList.value = tmp
      }
    },
    { immediate: true }
  )
  // 预览图片
  const dialogVisiblePdf = ref()
  const pdfUrl = ref()
  const previewIndex = ref()
  const preview = function (file) {
    console.log('listObj =' + JSON.stringify(listObj.value))
    let tmpUrl = file.url
    const { response } = file
    if (response && response.data) tmpUrl = response.data

    const list1 = Object.keys(listObj.value).map((v) => listObj.value[v].url)
    const list2 = defaultList.value.map((item) => item.url)

    const allMedia = list2.concat(list1)
    if (props.fileAccept === videoType) {
      playVideo(allMedia[0])
      return
    }
    console.log('file =' + JSON.stringify(file))
    if (
      common.getExtByName(file.url) === 'pdf' ||
      common.getExtByName(file.name) === 'pdf'
    ) {
      dialogVisiblePdf.value = true
      pdfUrl.value = tmpUrl
    } else {
      imageList.value = allMedia.filter(
        (item) => common.getExtByName(item) !== 'pdf'
      )
      imageList.value.forEach((item, index) => {
        if (item === tmpUrl) previewIndex.value = index
      })
    }
  }

  const closeImgViewer = function () {
    imageList.value = []
  }

  const handleRemove = function (file) {
    // const list = defaultList.value.filter((item) => item.uid !== file.uid)
    // if (list.length < defaultList.value.length) {
    //   defaultList.value = list
    //   return
    // }
    // removeFile(file)
    deleteFunc(file)
  }

  const uploadError = function (error, file, uploadFiles) {
    // 兼容没有权限和断网
    if (error && !file) {
      common.XmMessage(1, error.response.message)
      deleteFunc(error)
    } else {
      common.XmMessage(
        1,
        `文件${file.name}上传失败，请减少体积或检查网络后重试`
      )
      deleteFunc(file)
    }
    // if (file.name) {
    //   common.XmMessage(
    //     1,
    //     `文件${file.name}上传失败，请减少体积后重试，或联系客服`
    //   )
    // }
    // deleteFunc(file)
  }
  const handleSuccess = function (response, file) {
    if (response.code === '0000') {
      uploadSuccess(response, file)
    } else {
      uploadError(file)
    }
  }
  const beforeUpload = function (file) {
    if (props.maxFileSize && file.size > props.maxFileSize * 1024 * 1024) {
      common.XmMessage(1, `上传失败，视频大小不能大于${props.maxFileSize}M`)
      return false
    }
    return uploadBefore(file)
  }
  const onExceed = function () {
    common.XmMessage(1, `上传失败，已上传最大值 ${props.max}`)
  }
  const getStatus = function () {
    if (browserVersion.value <= 74 && browserVersion.value >= 71) {
      const list = defaultList.value.filter(
        (item) => item.status === 'uploading'
      )
      if (list.length > 0) {
        return false
      } else {
        const list = Object.keys(defaultList.value).map((v) => {
          const item = defaultList.value[v]
          return {
            name: item.name,
            uid: item.uid,
            url: item.url,
          }
        })
        emits('update:modelValue', JSON.stringify(list))
        return true
      }
    }
    if (!checkAllSuccess()) {
      return false
    }
    const list = Object.keys(listObj.value).map((v) => {
      const item = listObj.value[v]
      return { name: common.getUrlName(item.url), uid: item.uid, url: item.url }
    })

    const allFile = defaultList.value.concat(list)

    emits('update:modelValue', JSON.stringify(allFile))

    listObj.value = {}
    return true
  }

  function deleteFunc(file) {
    const list = defaultList.value.filter((item) => item.uid !== file.uid)
    if (list.length < defaultList.value.length) {
      defaultList.value = list
      return
    }
    removeFile(file)
  }
  // 放给外部调用
  defineExpose({ getStatus })

  // antd 对上传失败的进行提示
  function antdHandleChange(params) {
    const { file, fileList } = params
    console.log('antdHandleChange 1 ')
    if (browserVersion <= 74 && browserVersion >= 71) {
      if (
        file.status === 'done' ||
        file.status === 'success' ||
        file.status === 'removed'
      ) {
        const file = fileList
          .filter((item) => item.status === 'success' || item.url)
          .map((item) => {
            return {
              name: item.name,
              url: (item.response && item.response.data) || item.url,
            }
          })
        const doFile = fileList
          .filter((item) => item.status === 'done')
          .map((item) => {
            return { name: item.name, url: item.response.data }
          })
        emits('update:modelValue', JSON.stringify(file.concat(doFile)))
      }
    }
  }

  const isVisble = ref(false)
  const videoUrl = ref()
  function playVideo(url) {
    if (url) {
      videoUrl.value = url
      isVisble.value = true
    } else {
      console.log('点击了暂无数据')
    }
  }

  const refPalyer = ref()
  const diaglogCloed = function () {
    if (refPalyer.value) refPalyer.value.pause()
  }
</script>
<script>
  import { defineComponent } from 'vue'

  export default defineComponent({
    name: 'FileUpload',
  })
</script>
<style lang="scss" scoped>
  // .upload-demo,
  // .ant-code-box-demo {
  //   max-width: 800px;
  // }
</style>
